package com.lambkit.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonKit {

    public static <T> T getObject(JSONObject json, String key, Class<T> type) {
        if(StrUtil.isNotBlank(key)) {
            String[] keys = key.trim().split("\\.");
            JSONObject res = json;
            for (int i=1; i< keys.length; i++) {
                String skey = keys[i-1];
                JSONObject obj = res.getJSONObject(skey);
                res = obj;
            }
            return res != null ? res.getObject(keys[keys.length-1], type) : null;
        }
        return null;
    }

    public static String getString(JSONObject json, String key) {
        return getObject(json, key, String.class);
    }

    public static Integer getInt(JSONObject json, String key) {
        return getObject(json, key, Integer.class);
    }

    public static Boolean getBoolean(JSONObject json, String key) {
        return getObject(json, key, Boolean.class);
    }

    public static JSONObject getJSONObject(JSONObject json, String key) {
        if(StrUtil.isNotBlank(key)) {
            String[] keys = key.trim().split(".");
            JSONObject res = json;
            for (String skey : keys) {
                JSONObject obj = res.getJSONObject(skey);
                res = obj;
            }
            return res;
        }
        return null;
    }

    public static JSONArray getJSONArray(JSONObject json, String key) {
        if(StrUtil.isNotBlank(key)) {
            String[] keys = key.trim().split("\\.");
            JSONObject res = json;
            for (int i=1; i< keys.length; i++) {
                String skey = keys[i-1];
                JSONObject obj = res.getJSONObject(skey);
                res = obj;
            }
            return res != null ? res.getJSONArray(keys[keys.length-1]) : null;
        }
        return null;
    }
}
